package com.lemon.smartsafetynew.ui.activity.hidden;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.NetResultBo;
import com.lemon.smartsafetynew.entity.contact.PersonVo;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.event.contact.PersonEvent;
import com.lemon.smartsafetynew.entity.hidden.ReviewSafeHiddenDto;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDownloadVo;
import com.lemon.smartsafetynew.net.services.SafeHiddenServices;
import com.lemon.smartsafetynew.ui.activity.contact.PersonListActivity;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.TimeFormatConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 复查隐患
 * Created by Andrew on 2017/9/11.
 */

public class SafeHiddenReviewActivity extends PhotoSelectBaseActivity {

    private static SafeHiddenDownloadVo safeHiddenDownloadVo;

    @Bind(R.id.hidden_review_department_tv)
    TextView hiddenReviewDepartmentTv;
    @Bind(R.id.hidden_review_person_tv)
    TextView hiddenReviewPersonTv;
    @Bind(R.id.hidden_review_time_tv)
    TextView hiddenReviewTimeTv;
    @Bind(R.id.review_remark_et)
    MaterialEditText reviewRemarkEt;

    @Bind(R.id.responsible_tv)
    TextView responsibleTv;
    @Bind(R.id.responsible_layout)
    LinearLayout responsibleLayout;
    @Bind(R.id.expect_finish_date_tv)
    TextView expectFinishDateTv;
    @Bind(R.id.expect_finish_date_layout)
    LinearLayout expectFinishDateLayout;
    @Bind(R.id.expect_money_et)
    EditText expectMoneyEt;

    @Bind(R.id.hidden_submit_btn)
    Button hiddenSubmitBtn;
    @Bind(R.id.hidden_reject_btn)
    Button hiddenRejectBtn;

    // ======== 人员 ========
    private PersonVo personVo;

    private User user;
    //每次提交唯一ID
    private String UUID = "";

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO)) {
                safeHiddenDownloadVo = (SafeHiddenDownloadVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO);
            }
        }

    }

    @Override
    protected void initTitle() {
        this.setBarTitle("隐患复查");
    }

    @Override
    protected void callFinish() {
        AppService.getBus().post(new ViewEvent(SafeHiddenReviewActivity.class.getName()));
        AppManager.getAppManager().finishActivity(SafeHiddenReviewActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_hidden_review;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initData();
        initCommon();

    }

    /**
     * 初始化
     */
    private void initCommon() {

        hiddenReviewDepartmentTv.setText(safeHiddenDownloadVo.getReview_dept());
        hiddenReviewPersonTv.setText(safeHiddenDownloadVo.getReview_user_name());
        //hiddenReviewTimeTv.setText(CommonUtil.secondToTimeStr(System.currentTimeMillis(), DateTypeEnum.DAY));

        responsibleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPersonList();
            }
        });

        expectFinishDateLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickFinishDate();
            }
        });

    }

    /**
     * 初始化
     */
    private void initData() {
        UUID = CommonUtil.getUUID();
        user = AccountUtil.getUser();
    }

    /**
     * 验证隐患通过的表单
     */
    private boolean verifyParam() {

//        if (StringUtils.isEmpty(hiddenReviewTimeTv.getText().toString().trim())) {
//            mHUDUtil.showErrorTip("请选择复查时间");
//            return false;
//        }

        if (StringUtils.isEmpty(reviewRemarkEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请输入复查结果");
            return false;
        }

        return true;

    }

    /**
     * 验证隐患不通过的表单
     */
    private boolean verifyParamNotPass() {

//        if (StringUtils.isEmpty(hiddenReviewTimeTv.getText().toString().trim())) {
//            mHUDUtil.showErrorTip("请选择复查时间");
//            return false;
//        }

        if (StringUtils.isEmpty(reviewRemarkEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请输入复查结果");
            return false;
        }


        /**
         * 责任人
         */
        if (StringUtils.isEmpty(responsibleTv.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择责任人。");
            return false;
        }

        /**
         * 预计完成时间
         */
        if (StringUtils.isEmpty(expectFinishDateTv.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择预计完成时间。");
            return false;
        }

        //【常熟项目】不需要
        /**
         * 预计整改金额
         */
//        if (StringUtils.isEmpty(expectMoneyEt.getText().toString().trim())) {
//
//            mHUDUtil.showErrorTip("请填写预计整改金额。");
//            return false;
//
//        } else {
//
//            String str = expectMoneyEt.getText().toString().trim();
//
//            Pattern r = Pattern.compile(SafeCloudConstants.MONEY_INPUT_REGULAR_EXPRESSION);
//            Matcher m = r.matcher(str);
//
//            if(m.matches()) {
//                //return true;
//            } else {
//                mHUDUtil.showErrorTip("输入的预计整改金额超过最大值。");
//                return false;
//            }
//
//        }
        //【常熟项目】不需要

        return true;

    }

    @OnClick({R.id.hidden_submit_btn, R.id.hidden_review_time_layout, R.id.hidden_reject_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.hidden_submit_btn:
                hiddenSubmitBtn.setEnabled(false);
                hiddenRejectBtn.setEnabled(false);
                if (verifyParam()) {
                    submitReviewResult(false); //关闭隐患
                } else {
                    hiddenSubmitBtn.setEnabled(true);
                    hiddenRejectBtn.setEnabled(true);
                }
                break;
            case R.id.hidden_reject_btn:
                hiddenSubmitBtn.setEnabled(false);
                hiddenRejectBtn.setEnabled(false);
                if (verifyParamNotPass()) {
                    submitReviewResult(true); //退回隐患
                } else {
                    hiddenSubmitBtn.setEnabled(true);
                    hiddenRejectBtn.setEnabled(true);
                }
                break;
            case R.id.hidden_review_time_layout:
                //pickCheckDate();
                break;
        }
    }

    /**
     * 提交复查记录
     *
     * @param reject true: 退回隐患
     *               flase：关闭隐患
     */
    private void submitReviewResult(boolean reject) {

        mHUDUtil.showHUD();

        final LemonRequestParams params = new LemonRequestParams("");

        ReviewSafeHiddenDto rectifySafeHiddenDto = new ReviewSafeHiddenDto();
        rectifySafeHiddenDto.setReview_user_id(user.getUserId());
        rectifySafeHiddenDto.setReview_user_name(user.getUserName());
        rectifySafeHiddenDto.setRemark(reviewRemarkEt.getText().toString().trim());
        rectifySafeHiddenDto.setDanger_id(safeHiddenDownloadVo.getId());

        if (reject) {
            //TODO
            params.put("rectify_user_name", personVo.getUser_name());
            params.put("rectify_user_id", personVo.getUser_id());
            params.put("plan_rectify_time", expectFinishDateTv.getText().toString().trim());
            //params.put("plan_rectify_money", expectMoneyEt.getText().toString().trim()); //【常熟项目】不需要
        }

        params.put("data", mGson.toJson(rectifySafeHiddenDto));
        params.put("submit_uuid", UUID);

        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                getUploadMediaItems(new SelectEvidenceAdapter.CropCallBack<Map<String, File>>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFinish(Map<String, File> data) {

                        if (data.isEmpty()) {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hiddenSubmitBtn.setEnabled(true);
                                    hiddenRejectBtn.setEnabled(true);
                                    mHUDUtil.showErrorTip("复查操作必须添加附件。");
                                }
                            });

                        } else {
                            SafeHiddenServices
                                    .init()
                                    .reviewHidden(params, data);
                        }
                    }
                });
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {
        if (KeyConstants.URL_REVIEW_SAFE_HIDDEN.equals(event.getTag())) {                            //复查隐患  有附件
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                //mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                hiddenSubmitBtn.setEnabled(true);
                hiddenRejectBtn.setEnabled(true);
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip("提交成功", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    if (event.getCode() == NetResultBo.Code.REPEAT_SUBMIT.getCode()) {
                        //此处为过滤重复提交的错误，此错误不需要做任何提示

                    } else {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }

                }
            }
        } else if (KeyConstants.URL_REVIEW_SAFE_HIDDEN_NO_FILE.equals(event.getTag())) {             //复查隐患  无附件
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                //mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                hiddenSubmitBtn.setEnabled(true);
                hiddenRejectBtn.setEnabled(true);
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip("提交成功", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    if (event.getCode() == NetResultBo.Code.REPEAT_SUBMIT.getCode()) {
                        //此处为过滤重复提交的错误，此错误不需要做任何提示

                    } else {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }

                }
            }
        }
    }


    /**
     * 选择复查日期
     */
    private void pickCheckDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat dateFormat = new SimpleDateFormat(TimeFormatConstants.FORMAT_DATE, Locale.getDefault());
                String dateStr = dateFormat.format(calendar.getTime());

                hiddenReviewTimeTv.setText(CommonUtil.avoidNullString(dateStr));

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), Constants.DIALOG_TAG_CHECK_DATE);
    }

    /**
     * 预计完成日期
     */
    private void pickFinishDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                Calendar calendar = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                now.setTime(calendar.getTime());

                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat dateFormat = new SimpleDateFormat(TimeFormatConstants.FORMAT_DATE, Locale.getDefault());
                String dateStr = dateFormat.format(calendar.getTime());

                if (now.after(calendar)) {
                    mHUDUtil.showErrorTip("预计完成时间不能早于当前时间。");
                    return;
                }
                expectFinishDateTv.setText(CommonUtil.avoidNullString(dateStr));

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), Constants.DIALOG_TAG_CHECK_DATE);
    }

    /**
     * 选择人员
     */
    private void showPersonList() {
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstants.KEY_TAG, SafeHiddenReviewActivity.class.getName());
        bundle.putString(KeyConstants.KEY_COMPANY_ID, safeHiddenDownloadVo.getCompany_id());
        UIHelper.showActivity(SafeHiddenReviewActivity.this, bundle, PersonListActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPersonEvent(PersonEvent event) {

        if (SafeHiddenReviewActivity.class.getName().equals(event.getTag())) {
            personVo = event.getPersonVo();
            responsibleTv.setText(CommonUtil.avoidNullString(personVo.getUser_name()));
        }
    }

}
